package com.demo.demo.images;

import cn.hutool.core.util.StrUtil;
import com.google.common.base.Stopwatch;
import com.google.common.collect.Maps;

import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.plugins.jpeg.JPEGImageWriteParam;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * Copyright
 *
 * @Author WuHuang
 * @Date 2023/5/11
 */
@Slf4j
public class MergeImages2 {




    public static void main(String[] args) {
        HashMap<String, Object> map = mergeMaterialImage("https://sh-staging-changyi-wecom20-01.oss-cn-shanghai.aliyuncs.com/2023/05/17/4a81f8a8-4c0a-453c-9fe5-7fbc1e0a149e.png"
                , "1030.00", "1080.00", "测试一下测试一下测试一下测试一下测试一下测试一下测试一下测试一下");
        System.out.println(map);
    }

    public static HashMap<String, Object> mergeMaterialImage(String originalUrl, String originalPrice, String promotionPrice, String styleName) {
        Stopwatch stopwatch = Stopwatch.createStarted();
        BufferedImage image1 = null;
        BufferedImage image2 = null;
        try {
            // 加载第一张图片
            URL labelUrl = new URL("https://sh-staging-changyi-wecom20-01.oss-cn-shanghai.aliyuncs.com/template/material_images_label.png");
            URLConnection connection = labelUrl.openConnection();
            connection.setConnectTimeout(2000); // 设置连接超时时间为2秒
            connection.setReadTimeout(2000); // 设置读取数据超时时间为2秒
            image1 = ImageIO.read(connection.getInputStream());
            // 加载第二张图片
            URL url = new URL(originalUrl);
            URLConnection urlConnection = url.openConnection();
            urlConnection.setConnectTimeout(3000); // 设置连接超时时间为2秒
            urlConnection.setReadTimeout(3000); // 设置读取数据超时时间为2秒
            image2 = ImageIO.read(urlConnection.getInputStream());
        } catch (IOException e) {
            log.error("MergeImages.mergeMaterialImage 读取图片 error:{}", e.getMessage(), e);

        }
        Graphics2D g = image1.createGraphics();
        //读取字体
        File file = new File("/usr/share/fonts/truetype/PingFang.ttc");
        mergerLabel(g, image1, originalPrice, promotionPrice, file);

        if (StrUtil.isNotEmpty(styleName)) {
            mergerImagesv2(g, image2, styleName, file);
        }

        log.info("MergeImages.mergeMaterialImage.success time:{}", stopwatch.elapsed(TimeUnit.SECONDS));
        return mergeMaterialImagesUploadFile(g, image1, image2, originalUrl);
    }

    public  static HashMap<String, Object> mergeMaterialImagesUploadFile(Graphics2D g, BufferedImage image1, BufferedImage image2, String originalUrl) {
        InputStream is = null;
        HashMap<String, Object> map = Maps.newHashMap();
        try {
            // 创建新的 BufferedImage，指定宽度和高度
            BufferedImage combined = new BufferedImage(image2.getWidth(), image2.getHeight(), BufferedImage.TYPE_INT_ARGB);
            // 获取 Graphics2D 对象
            g = (Graphics2D) combined.getGraphics();
            // 在背景色上绘制第二张图片
            g.drawImage(image2, 0, 0, null);
            // 在右上角绘制第一张图片
            int x = image2.getWidth() - image1.getWidth();
            int y = 0;
            g.drawImage(image1, x, y, null);
            g.dispose();
            String extension = extractFilename(originalUrl);
            // 保存结果
            File outputFile = new File("D:\\WorkSpace\\wu\\spring-boot-study\\springboot-demo\\src\\main\\resources\\output8.png");
            ImageIO.write(combined, "png", outputFile);
//            is = new ByteArrayInputStream(os.toByteArray());
//            String fileName = DateUtils.datePath() + "/" + IdUtils.fastUUID() + "." + extension;
//            String mergeUrl = OssUtils.uploadFile(bucketName, fileName, is);
//            map.put("mergeUrl", mergeUrl);
            return map;
        } catch (IOException e) {
            log.error("MergeImages.mergeMaterialImage 图片最终合成并上传 error:{}", e.getMessage(), e);

        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    public static BufferedImage compressImage(BufferedImage inputImage, float compressionQuality) throws IOException {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ByteArrayInputStream inputStream = null;
        ImageWriter writer = null;
        try {
            // 找到 JPEG 图像编码器
            writer = ImageIO.getImageWritersByFormatName("jpeg").next();
            JPEGImageWriteParam param = new JPEGImageWriteParam(null);
            // 设置压缩质量参数
            param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
            param.setCompressionQuality(compressionQuality);
            // 将图像写入输出流中
            writer.setOutput(ImageIO.createImageOutputStream(outputStream));
            writer.write(null, new IIOImage(inputImage, null, null), param);
            // 使用字节数组流创建输入流
            inputStream = new ByteArrayInputStream(outputStream.toByteArray());
            // 从输入流中读取图片数据并返回 BufferedImage
            BufferedImage outputImage = ImageIO.read(inputStream);
            return outputImage;
        } finally {
            // 关闭流资源，注意需要判空
            if (outputStream != null) {
                outputStream.close();
            }
            if (inputStream != null) {
                inputStream.close();
            }
            if (writer != null) {
                writer.dispose();
            }
        }
    }

    public static String extractFilename(String originalUrl) {
        String extension = "png";
        // 获取最后一个 "." 出现的位置
        int dotIndex = originalUrl.lastIndexOf(".");
        // 如果 "." 存在并且不在最后一位，则获取文件后缀
//        if (dotIndex > 0 && dotIndex < originalUrl.length() - 1) {
//            extension = originalUrl.substring(dotIndex + 1);
//        }
        return extension;
    }


    private static void mergerLabel(Graphics2D g, BufferedImage resizedImage, String originalPrice, String promotionPrice, File file) {
        try {
            // 获取 Graphics2D 对象
            g = (Graphics2D) resizedImage.getGraphics();
//            Font font = Font.createFont(Font.TRUETYPE_FONT, file).deriveFont(Font.BOLD, 62);
            Font font = new Font("PingFang SC", Font.BOLD, 62);
            // 第一个价格标签
            String price1 = "活动价: ¥" + originalPrice;
            int x1 = 44;
            int y1 = 65;
            addPriceTag(g, price1, x1, y1, font, Color.WHITE, false);
            // 第二个价格标签
//            Font font2 = Font.createFont(Font.TRUETYPE_FONT, file).deriveFont(Font.BOLD, 58);
            Font font2 = new Font("PingFang SC", Font.BOLD, 58);
            String price2 = "吊牌价: ¥" + promotionPrice;
            int x2 = 77;
            int y2 = 250;
            addPriceTag(g, price2, x2, y2, font2, Color.BLACK, true);
        } catch (Exception e) {
            log.error("MergeImages.mergerLabel error:{}", e.getMessage(), e);

        }
    }

    private static void mergerImages(Graphics2D g, BufferedImage image2, String labelText, File file) {
        // 获取新图像的图形对象
        g = image2.createGraphics();
        // 将原始图像绘制到新图像上
        g.drawImage(image2, 0, 0, null);
        // 在新图像的中心填充一个半透明的黑色矩形
        int labelWidth = 1800;
        int labelHeight = 320;
        int labelX = (image2.getWidth() - labelWidth) / 2;
        int labelY = (image2.getHeight() - labelHeight);
        g.setColor(new Color(0, 0, 0, 128));
        g.fillRect(0, labelY, labelWidth, labelHeight);

        // Add the label text to the new image
        g.setColor(Color.WHITE);
        g.setFont(new Font("PingFang SC", Font.BOLD, 106));
        int stringWidth = g.getFontMetrics().stringWidth(labelText);
        int x = labelX + (labelWidth - stringWidth) / 2;
        int y = labelY + ((labelHeight - g.getFontMetrics().getHeight()) / 2) + g.getFontMetrics().getAscent();
        g.drawString(labelText, x, y);
    }
    private static void mergerImagesv2(Graphics2D g, BufferedImage image2, String labelText, File file) {
        // 获取新图像的图形对象
        g = image2.createGraphics();
        // 将原始图像绘制到新图像上
        g.drawImage(image2, 0, 0, null);
        // 在新图像的中心填充一个半透明的黑色矩形
        int labelWidth = 1800;
        int labelHeight = 320;
        int labelX = (image2.getWidth() - labelWidth) / 2;
        int labelY = (image2.getHeight() - labelHeight);
        g.setColor(new Color(0, 0, 0, 128));
        g.fillRect(0, labelY, labelWidth, labelHeight);

        // Add the label text to the new image
        g.setColor(Color.WHITE);
        g.setFont(new Font("PingFang SC", Font.BOLD, 106));
        int maxLabelWidth = labelWidth - 40; // 剩余空间最多容纳的字符宽度
        int stringWidth = g.getFontMetrics().stringWidth(labelText); // 字符串宽度
        if (stringWidth > maxLabelWidth) {
            char[] chars = labelText.toCharArray();
            int endIndex = 0;
            int sumWidth = 0;
            for (int i = 0; i < chars.length; i++) {
                char c = chars[i];
                if (c >= '\u4e00' && c <= '\u9fa5') { // 判断是否为汉字
                    sumWidth += g.getFontMetrics().charsWidth(chars, i, 1);
                    if (sumWidth > maxLabelWidth) {
                        endIndex = i - 1;
                        break;
                    }
                } else {
                    sumWidth += g.getFontMetrics().charWidth(c);
                    if (sumWidth > maxLabelWidth) {
                        endIndex = i - 1;
                        break;
                    }
                }
                endIndex = i;
            }
            labelText = labelText.substring(0, endIndex + 1);
        }
        int x = labelX + (labelWidth - g.getFontMetrics().stringWidth(labelText)) / 2;
        int y = labelY + ((labelHeight - g.getFontMetrics().getHeight()) / 2) + g.getFontMetrics().getAscent();
        g.drawString(labelText, x, y);

    }


    private static void addPriceTag(Graphics2D g2d, String price, int x, int y, Font font, Color textColor, boolean drawLine) {
        // 获取字体度量值
        FontMetrics fm = g2d.getFontMetrics(font);
        int textWidth = fm.stringWidth(price);
        int labelHeight = fm.getHeight();
        // 绘制文字
        g2d.setFont(font);
        g2d.setColor(textColor);
        g2d.drawString(price, x, y + labelHeight);
        // 绘制删除线
        if (drawLine) {
            g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
            g2d.drawLine(x + 200, y + 58, x + textWidth + 5, y + 58);

        }
    }

}
